import React from "react";
import {Button, Col, DatePicker, Form, Icon, Input, InputNumber, message, Modal, Row, Spin, Upload} from "antd";
import TextArea from "antd/es/input/TextArea";
import {connect} from "dva";
import moment from 'moment';
import witty from "@/utils/wittyUtils";
import styles from "@/pages/user/register/Register.less";

const FormItem = Form.Item;
const {RangePicker} = DatePicker;

@connect(({elevatorModel, commonModel,}) => ({
    elevatorModel, commonModel,
}))
class EditElevator extends React.Component {

    state = {
        //-- 加载层
        loading: false,
        //-- 电梯详情数据
        editElevatorData: {},
        //-- 是否展示编辑框
        showEditElevator: false,
        //-- 处理方式
        handleType: '',
        //-- 电梯使用标志展示图
        useFlagPathShowCaseSelectedFile: null,
        //--电梯保险标志展示图
        insureFlagPathShowCaseSelectedFile: null,
    };

    componentDidMount() {
        const {onRef, parent} = this.props;
        this.parent = parent;
        if (onRef) {
            onRef(this);
        }
    }

    findPageData = function (params = {}) {
        const thisCtx = this;
        const {dispatch} = this.props;
        console.log(params);
        thisCtx.setState({loading: true});
        dispatch({
            type: 'elevatorModel/elevatorInfo',
            payload: params,
            callback: function (data) {
                thisCtx.setState({loading: false});
                console.log(data);
                if (data && data.success) {
                    if (data.datas.limitDate) {
                        data.datas.limitDateStart = data.datas.limitDate.split('至')[0];
                        data.datas.limitDateEnd = data.datas.limitDate.split('至')[1];
                    }
                    console.log(data.datas);
                    thisCtx.setState({
                        editElevatorData: data.datas,
                    })
                } else {
                    message.error('电梯详情获取失败');
                }
            }
        })
    }

    handlerEditElevator = (id) => {
        this.setState({
            showEditElevator: true,
            handleType: 'detail'
        });
        if (id) {
            this.findPageData({id});
        }
    }

    handlerCancel = () => {
        this.setState({
            showEditElevator: false,
            editElevatorData: {},
            useFlagPathShowCaseSelectedFile: null,
            insureFlagPathShowCaseSelectedFile: null,
        })
    }

    handleSubmit = (e) => {
        const thisCtx = this;
        const {dispatch} = this.props;
        const {useFlagPathShowCaseSelectedFile, insureFlagPathShowCaseSelectedFile, editElevatorData} = this.state;

        let fieldsValue = this.props.form.getFieldsValue();
        this.props.form.validateFieldsAndScroll((err, values) => {
            if (err) {
                return;
            }
            if (fieldsValue.limitDate) {
                fieldsValue.startDate = fieldsValue.limitDate[0].format('YYYY-MM-DD');
                fieldsValue.endDate = fieldsValue.limitDate[1].format('YYYY-MM-DD');
                delete fieldsValue.limitDate;
            }

            fieldsValue.id = editElevatorData.id;
            fieldsValue.validFlag = 1;

            thisCtx.setState({loading: true});

            const handleSubmitForm = () => {

                witty.validNilParams(fieldsValue);
                console.log(fieldsValue);
                dispatch({
                    type: 'elevatorModel/elevatorInfoListEdit',
                    payload: fieldsValue,
                    callback: function (data) {
                        thisCtx.setState({loading: false});
                        if (data && data.success) {
                            message.success('修改成功');
                            thisCtx.setState({
                                showEditElevator: false,
                            });
                            thisCtx.parent.findPageData();
                        } else {
                            message.error('电梯信息修改失败');
                        }
                    }
                });
            }

            if (witty.isValidObj(useFlagPathShowCaseSelectedFile)) {
                //-- 上传电梯使用标志图片
                this.fileUpload(
                    useFlagPathShowCaseSelectedFile.originFileObj,
                    '1',
                    function (useFlagPathData) {
                        fieldsValue['useFlagPath'] = useFlagPathData.datas.oss.filePath;
                        uploadInsureFlag();
                    },
                    function failCallback(data) {
                        message.error(data.msg);
                        thisCtx.setState({loading: false});
                    });
            } else {
                uploadInsureFlag();
            }

            function uploadInsureFlag() {
                if (witty.isValidObj(insureFlagPathShowCaseSelectedFile)) {
                    //-- 上传电梯保险标志图片
                    thisCtx.fileUpload(
                        insureFlagPathShowCaseSelectedFile.originFileObj,
                        '2',
                        function (insureFlagPathData) {
                            fieldsValue['insureFlagPath'] = insureFlagPathData.datas.oss.filePath;
                            handleSubmitForm();
                        },
                        function failCallback(data) {
                            message.error(data.msg);
                            thisCtx.setState({loading: false});
                        });
                } else {
                    handleSubmitForm();
                }
            }
        });
    }

    fileUpload = (file, formType, callback, failCallback) => {
        const {dispatch} = this.props;

        const formData = new window.FormData();

        formData.append('file', file);
        formData.append('formType', formType);
        formData.append('formId', '-1');

        dispatch({
            type: 'commonModel/fileUpload',
            payload: formData,
            callback: function (data) {
                if (!data.success) {
                    failCallback(data);
                } else {
                    if (witty.isValidObj(callback)) {
                        callback(data);
                    }
                }
            },
        });
    };

    render() {
        const thisCtx = this;
        const {getFieldDecorator} = this.props.form;

        let {showEditElevator, editElevatorData, handleType, loading, useFlagPathShowCaseSelectedFile, insureFlagPathShowCaseSelectedFile} = this.state;

        const uploadHandler = {
            accept: '.jpeg,.jpg,.png',
            listType: 'picture-card',
            className: 'avatar-uploader',
            showUploadList: false,
            //-- 上传前检测文件
            beforeUpload: function (file) {
                //-- 文件大小检测
                const checkFileSize = file.size / 1024 / 1024 < 10;
                if (!checkFileSize) {
                    message.error('文件必须小于10MB!');
                    return false;
                }
                return true;
            },

            onChange: function (info) {
                let status = info.file.status;

                if (status === 'uploading') return;

                witty.getImageFileBase64(info.file.originFileObj, image => {
                    info.file.base64 = image;
                    editElevatorData.useFlagPath = null;
                    thisCtx.setState({
                        useFlagPathShowCaseSelectedFile: info.file,
                        editElevatorData: editElevatorData,
                    });
                });
            },
        };

        const uploadHandler_insureFlagPath = {
            ...uploadHandler,
            onChange: function (info) {
                let status = info.file.status;

                if (status === 'uploading') return;

                witty.getImageFileBase64(info.file.originFileObj, image => {
                    info.file.base64 = image;
                    editElevatorData.insureFlagPath = null;
                    thisCtx.setState({
                        insureFlagPathShowCaseSelectedFile: info.file,
                        editElevatorData: editElevatorData
                    });
                });
            },
        };

        const formLayout = {
            layout: 'vertical',
            labelCol: {
                xs: 24,
                sm: 4
            },
            wrapperCol: {
                xs: 24,
                sm: 12
            }
        }

        const formItemLayout = {
            style: {
                margin: '0px',
            },
        }

        const colLayout = {
            span: 12,
        }

        const rowLayout = {
            gutter: 18,
        }
        const divLayout = {
            style: {
                padding: 0,
                margin: '0px 0px 0px 40px',
            }
        }

        return (
            <Modal
                visible={showEditElevator}
                footer={false}
                width={700}
                onCancel={() => this.handlerCancel()}
            >
                <Spin spinning={loading}>
                    <Form>
                        <Row {...rowLayout}>
                            <Col {...colLayout}>
                                <FormItem label={
                                    <span>
                                        特种设备使用标志
                                        <em style={{
                                            color: 'gray',
                                            fontStyle: 'normal'
                                        }}>(电梯)</em>
                                    </span>
                                } key={'useFlagPath'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>
                                                <img
                                                    style={{
                                                        height: 130,
                                                        width: 280,
                                                        borderRadius: 8,
                                                        backgroundImage: `url("${
                                                            witty.isValidObj(useFlagPathShowCaseSelectedFile)
                                                                ? useFlagPathShowCaseSelectedFile.base64
                                                                : editElevatorData.useFlagPath
                                                        }")`,
                                                        backgroundRepeat: 'no-repeat',
                                                        backgroundPosition: 'center',
                                                        backgroundSize: 'cover',
                                                    }}
                                                    onClick={() => {
                                                        window.open(editElevatorData.useFlagPath, '_blank');
                                                    }}/>
                                            </div>
                                            :
                                            getFieldDecorator('useFlagPath', {})(
                                                <Upload {...uploadHandler}>
                                                    {witty.isValidObj(useFlagPathShowCaseSelectedFile) || witty.isValidObj(editElevatorData.useFlagPath) ? (
                                                        <img
                                                            style={{
                                                                height: 130,
                                                                width: 280,
                                                                borderRadius: 8,
                                                                backgroundImage: `url("${
                                                                    witty.isValidObj(useFlagPathShowCaseSelectedFile)
                                                                        ? useFlagPathShowCaseSelectedFile.base64
                                                                        : editElevatorData.useFlagPath
                                                                }")`,
                                                                backgroundRepeat: 'no-repeat',
                                                                backgroundPosition: 'center',
                                                                backgroundSize: 'cover',
                                                            }}
                                                        />
                                                    ) : (
                                                        <div style={{
                                                            height: 130,
                                                            width: 280,
                                                            display: "flex",
                                                            alignItems: "center",
                                                            justifyContent: "center"
                                                            // textAlign: 'center',
                                                            // display: 'table-cell',
                                                            // verticalAlign: 'middle'
                                                        }}>
                                                            <Icon type={'plus'}/>
                                                            <div className="ant-upload-text">请选择图片</div>
                                                        </div>
                                                    )}
                                                </Upload>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'电梯保险标志'} key={'insureFlagPath'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>
                                                <img
                                                    style={{
                                                        height: 130,
                                                        width: 280,
                                                        borderRadius: 8,
                                                        backgroundImage: `url("${
                                                            witty.isValidObj(insureFlagPathShowCaseSelectedFile)
                                                                ? insureFlagPathShowCaseSelectedFile.base64
                                                                : editElevatorData.insureFlagPath
                                                        }")`,
                                                        backgroundRepeat: 'no-repeat',
                                                        backgroundPosition: 'center',
                                                        backgroundSize: 'cover',
                                                    }}
                                                    onClick={() => {
                                                        window.open(editElevatorData.insureFlagPath, '_blank');
                                                    }}/>
                                            </div>
                                            :
                                            getFieldDecorator('insureFlagPath', {})(
                                                <Upload {...uploadHandler_insureFlagPath}>
                                                    {witty.isValidObj(insureFlagPathShowCaseSelectedFile) ||
                                                    witty.isValidObj(editElevatorData.insureFlagPath) ? (
                                                        <img
                                                            style={{
                                                                height: 130,
                                                                width: 280,
                                                                borderRadius: 8,
                                                                backgroundImage: `url("${
                                                                    witty.isValidObj(insureFlagPathShowCaseSelectedFile)
                                                                        ? insureFlagPathShowCaseSelectedFile.base64
                                                                        : editElevatorData.insureFlagPath
                                                                }")`,
                                                                backgroundRepeat: 'no-repeat',
                                                                backgroundPosition: 'center',
                                                                backgroundSize: 'cover',
                                                            }}
                                                        />
                                                    ) : (
                                                        <div style={{
                                                            height: 130,
                                                            width: 280,
                                                            display: "flex",
                                                            alignItems: "center",
                                                            justifyContent: "center"
                                                        }}>
                                                            <Icon type={'plus'}/>
                                                            <div className="ant-upload-text">请选择图片</div>
                                                        </div>
                                                    )}
                                                </Upload>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'使用单位名称'} key={'uorgName'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.uorgName || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('uorgName', {
                                                initialValue: editElevatorData.uorgName,
                                            })(
                                                <Input type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'使用地址'} key={'location'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.location || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('location', {
                                                initialValue: editElevatorData.location,
                                            })(
                                                <Input type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'统一社会信用代码'} key={'ocode'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.ocode || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('ocode', {
                                                initialValue: editElevatorData.ocode,
                                            })(
                                                <Input type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'设备代码'} key={'elevatorCode'}  {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.elevatorCode || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('elevatorCode', {
                                                initialValue: editElevatorData.elevatorCode,
                                            })(
                                                <Input type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'设备编号'} key={'useNum'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.useNum || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('useNum', {
                                                initialValue: editElevatorData.useNum,
                                            })(
                                                <Input type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'维保单位'} key={'maintenance'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.maintenance || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('maintenance', {
                                                initialValue: editElevatorData.maintenance,
                                            })(
                                                <Input type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'保障期限'} key={'limitDate'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.limitDate || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('limitDate', {
                                                initialValue: [editElevatorData.limitDateStart ? moment(editElevatorData.limitDateStart, 'YYYY-MM-DD') : null, editElevatorData.limitDateEnd ? moment(editElevatorData.limitDateEnd, 'YYYY-MM-DD') : null]
                                            })(
                                                <RangePicker showTime={true} format={'YYYY-MM-DD'}
                                                             style={{width: '100%'}}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'原保费'} key={'price'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.price || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('price', {
                                                initialValue: editElevatorData.price,
                                            })(
                                                <InputNumber style={{width: '100%'}} type={'primary'}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'用户名'} {...formItemLayout}>
                                    {
                                        <div {...divLayout}>{editElevatorData.userName || '暂无数据'}</div>
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'上传时间'} {...formItemLayout}>
                                    {
                                        <div {...divLayout}>{editElevatorData.createTime || '暂无数据'}</div>
                                    }
                                </FormItem>
                            </Col>
                            <Col {...colLayout}>
                                <FormItem label={'备注'} {...formItemLayout}>
                                    {
                                        (handleType == 'detail' && editElevatorData) ?
                                            <div {...divLayout}>{editElevatorData.remark || '暂无数据'}</div>
                                            :
                                            getFieldDecorator('remark', {
                                                initialValue: editElevatorData.remark,
                                            })(
                                                <TextArea autoSize={{
                                                    minRows: 3,
                                                    maxRows: 3
                                                }}/>
                                            )
                                    }
                                </FormItem>
                            </Col>
                        </Row>

                        <Row>
                            {(handleType == 'detail') ?
                                <Col span={24} style={{textAlign: 'center', height: '32px', lineHeight: '32px'}}>
                                    <FormItem wrapperCol={{xs: 24, sm: 24, md: 24, lg: 24}}>
                                        <Button type={'primary'} style={{margin: '0 20px'}}
                                                onClick={() =>
                                                    this.setState({
                                                        handleType: 'edit',
                                                    })
                                                }>编辑</Button>
                                    </FormItem>
                                </Col>
                                :
                                <Col span={24} style={{textAlign: 'center', height: '32px', lineHeight: '32px'}}>
                                    <FormItem wrapperCol={{xs: 24, sm: 24, md: 24, lg: 24}}>
                                        <Button type={'primary'} style={{margin: '0 20px'}}
                                                onClick={() => this.handleSubmit()}>保存</Button>
                                        <Button onClick={() => this.handlerCancel()}>取消</Button>
                                    </FormItem>
                                </Col>
                            }
                        </Row>
                    </Form>
                </Spin>
            </Modal>
        );
    }

}

export default Form.create()(EditElevator);
